import React from "react";
import { $api } from '@/http/api'
import { useParams } from 'react-router-dom'
import FoodItem from "./components/FoodItem"
import Masonry from 'react-masonry-css'
import { Form, Input, Modal, Button, InputNumber, Upload, message, Empty } from 'antd'
import { PlusOutlined } from '@ant-design/icons'

const { TextArea } = Input;

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

const withRouter = (Component) => {
  return (props) => (
    <Component {...props} params={useParams()} />
  )
}

class Menu extends React.Component {
  formRef = React.createRef()
  state = {
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    foodList: [],
    isModalVisible: false,
    fileList: []
  }

  handleCancel = () => {
    this.setState({
      isModalVisible: false
    })
    this.onReset()
  }

  newFood = (values) => {
    if (values.file[0] === undefined) {
      message.error("Please select a picture!")
    } else {
      $api.manager.addFood({
        name: values.name,
        price: values.price,
        description: values.description,
        restaurant_id: this.props.params.id,
        file: values.file[0].originFileObj
      }).then((res) => {
        if (res.code === 200) {
          message.success("Add food successfully!")
          this.refresh()
          this.handleCancel()
        }
      })
    }
  }

  addFood = () => {
    this.setState({
      isModalVisible: true
    })
  }

  componentDidMount() {
    this.refresh()
  }

  normFile = (e) => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  refresh = () => {
    $api.manager.getRestaurantInfo({
      id: this.props.params.id
    }).then((res) => {
      if (res.code === 200) {
        this.setState({
          foodList: res.data.foodList
        })
      }
    })
  }

  onReset = () => {
    this.formRef.current.resetFields()
    this.setState({ fileList: [] })
  }

  handleChange = ({ fileList }) => this.setState({ fileList });

  cancelPreview = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

  render() {
    const { previewVisible, previewImage, fileList, previewTitle } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    )

    const uploadProps = {
      beforeUpload: file => {
        const isIMG = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg';
        if (!isIMG) {
          message.error(`${file.name} is not a image file`);
        }
        return false
      },
      listType: "picture-card"
    }

    let list = null
    if (this.state.foodList.length === 0) {
      list = <Empty description="There is no food in the menu." className='pt-8' />
    } else {
      list =
        <Masonry
          breakpointCols={{ 640: 1, 1024: 2, 1280: 3, default: 4 }}
          className="my-masonry-grid"
          columnClassName="my-masonry-grid_column">
          {this.state.foodList.map((item, index) => {
            return (
              <div key={index}>
                <FoodItem {...item} refresh={this.refresh} />
              </div>
            )
          })}
        </Masonry>
    }

    return (
      <>
        <div className='mb-4'>
          <Button onClick={this.addFood}>Add Food</Button>
        </div>
        {list}
        <Modal title="New Food" visible={this.state.isModalVisible} footer={null} onCancel={this.handleCancel}>
          <Form ref={this.formRef} name="basic" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} onFinish={this.newFood}>
            <Form.Item label="Food Name" name="name" rules={[{ required: true, message: 'Please input the food name!' }]} >
              <Input />
            </Form.Item>
            <Form.Item label="Price" name="price" rules={[{ required: true, message: 'Please input the food price!' }]} >
              <InputNumber />
            </Form.Item>
            <Form.Item label="Description" name="description" >
              <TextArea rows={4} />
            </Form.Item>
            <Form.Item label="Food Picture" name="file" valuePropName="fileList" getValueFromEvent={this.normFile}>
              <Upload fileList={fileList} {...uploadProps} maxCount={1} onChange={this.handleChange} onPreview={this.handlePreview}>
                {fileList.length > 0 ? null : uploadButton}
              </Upload>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button onClick={this.handleCancel} className='mr-4'>Cancel</Button>
              <Button type="primary" htmlType="submit">OK</Button>
              <Button onClick={this.onReset} className='ml-4'>Reset</Button>
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.cancelPreview}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    )
  }
}

export default withRouter(Menu);